import wx
import psutil
import matplotlib.pyplot as plt
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
import colorsys

# 确保 matplotlib 使用 Agg 后端
plt.switch_backend('Agg')


class percentPanel(wx.Panel):
    def __init__(self, parent, title, data_name):
        wx.Panel.__init__(self, parent)
        self.title = title
        self.data_name = data_name

        self.axes_x = []
        self.figure = plt.figure()
        self.axes = self.figure.add_subplot()
        self.axes.set_ylim(0, 100)
        self.axes.set_xlim(0, 100)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()
        self.init_data()

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
        self.timer.Start(1000)

    def init_data(self):
        self.cpu_count = psutil.cpu_count()
        self.mem_count = 1

        self.line = {}
        self.time_no = 0
        self.axes_x = []
        self.cpu_percent = {}
        self.mem_percent = {}

        if self.data_name == 'cpu':
            for i in range(self.cpu_count):
                self.cpu_percent[i] = []
                color = self.get_color(i)
                (temp,) = self.axes.plot([], [], linewidth=1, color=color)

                self.line[str(i)] = temp
        elif self.data_name == "mem":
            for i in range(self.mem_count):
                self.mem_percent[i] = []
                color = self.get_color(i + self.cpu_count)
                (temp,) = self.axes.plot([], [], linewidth=1, color=color)
                self.line[str(i)] = temp

    def get_color(self, i):
        return colorsys.hsv_to_rgb(i / self.cpu_count, 1, 1)  # 颜色

    def get_cpu_percent(self):
        cpu_id = 0
        percent = psutil.cpu_percent(interval=1, percpu=True)
        for item in percent:
            self.cpu_percent[cpu_id].append(item)
            cpu_id += 1

    def get_mem_percent(self):
        percent = psutil.virtual_memory().percent
        self.mem_percent[0].append(percent)

    def on_timer(self, event):
        if self.data_name == 'cpu':
            self.axes_x.append(self.time_no)
            self.time_no += 1
            self.get_cpu_percent()
            j = 0
            for item in self.cpu_percent:
                self.line[str(j)].set_data(self.axes_x,
                                           self.cpu_percent[item])

                j += 1
        elif self.data_name == "mem":
            self.axes_x.append(self.time_no)
            self.time_no += 1
            self.get_mem_percent()
            j = 0
            for item in self.mem_percent:
                self.line[str(j)].set_data(self.axes_x,
                                           self.mem_percent[item])
                j += 1
        self.canvas.draw()


class MainFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(800, 600))

        self.panel = (percentPanel(self, title="CPU Usage", data_name="cpu"))  # 传递 title 和 data_name 参数
        self.Show()


if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame(None, "wxPython Matplotlib Example")
    app.MainLoop()

# 1定时器线程：
# 使用 threading.Thread 启动一个线程来定期更新数据。
# update_data 方法每秒调用一次 get_cpu_percent 或
# get_mem_percent 方法来更新数据，并调用 update_plot 方法来刷新图表。
# 2数据更新和图表刷新：
# get_cpu_percent 方法获取每个 CPU 核心的使用率，并将其存储在 self.cpu_percent 字典中。
# update_plot 方法更新图表中的数据，并重新绘制图表。
# 3数据存储优化：
# 限制每个 CPU 核心的使用率数据长度为 100，以避免内存占用过高。
# import wx
# import psutil
# import matplotlib.pyplot as plt
# from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
# import colorsys
# import threading
# import time
#
# # 确保 matplotlib 使用 Agg 后端
# plt.switch_backend('Agg')
#
# class percentPanel(wx.Panel):
#     def __init__(self, parent, title, data_name):
#         wx.Panel.__init__(self, parent)
#         self.title = title
#         self.data_name = data_name
#
#         self.axes_x = []
#         self.figure = plt.figure()
#         self.axes = self.figure.add_subplot()
#         self.axes.set_ylim(0, 100)
#         self.axes.set_xlim(0, 100)
#         self.canvas = FigureCanvas(self, -1, self.figure)
#
#         self.sizer = wx.BoxSizer(wx.VERTICAL)
#         self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
#         self.SetSizer(self.sizer)
#         self.Fit()
#         self.init_data()
#
#         # 启动线程定期更新数据
#         self.update_thread = threading.Thread(target=self.update_data)
#         self.update_thread.daemon = True
#         self.update_thread.start()
#
#     def init_data(self):
#         self.cpu_count = psutil.cpu_count()
#         self.mem_count = 1
#
#         self.line = {}
#         self.time_no = []
#         self.axes_x = []
#         self.cpu_percent = {}
#         self.mem_percent = {}
#
#         if self.data_name == 'cpu':
#             for i in range(self.cpu_count):
#                 self.cpu_percent[i] = []
#                 color = self.get_color(i)
#                 (temp,) = self.axes.plot([], [], linewidth=1, color=color)
#
#                 self.line[str(i)] = temp
#         elif self.data_name == "mem":
#             for i in range(self.mem_count):
#                 self.mem_percent[i] = []
#                 color = self.get_color(i + self.cpu_count)
#                 (temp,) = self.axes.plot([], [], linewidth=1, color=color)
#
#     def get_color(self, i):
#         return colorsys.hsv_to_rgb(i / (self.cpu_count + self.mem_count), 1, 1)  # 颜色
#
#     def get_cpu_percent(self):
#         cpu_id = 0
#         percent = psutil.cpu_percent(interval=1, percpu=True)
#         for item in percent:
#             self.cpu_percent[cpu_id].append(item)
#             if len(self.cpu_percent[cpu_id]) > 100:  # 只保留最近100个数据点
#                 self.cpu_percent[cpu_id].pop(0)
#             cpu_id += 1
#
#     def get_mem_percent(self):
#         percent = psutil.virtual_memory().percent
#         self.mem_percent[0].append(percent)
#         if len(self.mem_percent[0]) > 100:  # 只保留最近100个数据点
#             self.mem_percent[0].pop(0)
#
#     def update_data(self):
#         while True:
#             if self.data_name == 'cpu':
#                 self.get_cpu_percent()
#             elif self.data_name == 'mem':
#                 self.get_mem_percent()
#             self.update_plot()
#             time.sleep(1)  # 每秒更新一次
#
#     def update_plot(self):
#         for i in range(len(self.cpu_percent)):
#             self.line[str(i)].set_data(range(len(self.cpu_percent[i])), self.cpu_percent[i])
#         self.axes.relim()
#         self.axes.autoscale_view()
#         self.canvas.draw_idle()
#
# class MainFrame(wx.Frame):
#     def __init__(self, parent, title):
#         wx.Frame.__init__(self, parent, title=title, size=(800, 600))
#         self.panel = percentPanel(self, title="CPU Usage", data_name="cpu")  # 传递 title 和 data_name 参数
#         self.Show()
#
# if __name__ == '__main__':
#     app = wx.App(False)
#     frame = MainFrame(None, "wxPython Matplotlib Example")
#     app.MainLoop()
